package com.unionpay.main;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.core.UriBuilder;

import com.sun.grizzly.http.SelectorThread;
import com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory;
import com.unionpay.config.Config;

/**
 * Main方法运行服务
 * 
 * @author liuzy
 * @since 2016年4月29日
 */
public class MainStart {
	public static void main(String[] args) throws IOException {
		int port = 8080;
		try {
			port = Integer.parseInt(args[0]);
		} catch (Exception e) {
			port = 8080;
		}
		Config.init("config.properties");
		final URI BASE_URI = UriBuilder.fromUri("http://127.0.0.1/rest/").port(port).build();
		Map<String, String> initParams = new HashMap<String, String>();
		initParams.put("com.sun.jersey.config.property.packages", "com.unionpay.resource");
		initParams.put("com.sun.jersey.api.json.POJOMappingFeature", "true");
		SelectorThread threadSelector = GrizzlyWebContainerFactory.create(BASE_URI, initParams);
		System.out.println(String.format("Jersey app started with WADL available at " + "%sapplication.wadl\nHit enter to stop it...", BASE_URI));
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					URL url = new URL(BASE_URI.toURL().toString() + "application.wadl");
					url.openConnection();
					url.openStream().close();
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
		
		// 控制台有输入，程序结束
		System.in.read();
		threadSelector.stopEndpoint();
		Config.destroy();
	}
}
